package com.athu.study.controller;

import com.athu.study.service.ChatAssistant;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@Slf4j
public class StreamingChatModelController {
    @Resource
    private StreamingChatModel streamingChatModel;
    @Resource
    private ChatAssistant chatAssistant;
    @GetMapping(value = "chatstream/chat")
    public Flux<String> chat(@RequestParam(value = "prompt",defaultValue = "石原里美")String prompt){
        return Flux.create(stringfluxsink->{
            streamingChatModel.chat(prompt, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String s) {
                    stringfluxsink.next(s);
                }

                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {
                    stringfluxsink.complete();
                }

                @Override
                public void onError(Throwable throwable) {
                    stringfluxsink.error(throwable);
                }
            });
        });
    }

    @GetMapping(value = "/chatstream/chat1")
    public Flux<String> chat1(@RequestParam(value = "prompt",defaultValue = "怎么高效学习")String prompt){
        return chatAssistant.chatFlux(prompt);
    }
}
